<template>
  <div class="category-grid">
    <!-- 标题 -->
    <div v-if="title" class="category-header">
      <h2 class="category-title">{{ title }}</h2>
      <el-button
        v-if="showMore"
        type="primary"
        link
        @click="handleViewMore"
      >
        查看更多 <el-icon><ArrowRight /></el-icon>
      </el-button>
    </div>

    <!-- 分类网格 -->
    <div v-if="!loading && categories.length > 0" class="category-list">
      <div
        v-for="category in displayCategories"
        :key="category.id"
        class="category-item"
        @click="handleCategoryClick(category)"
      >
        <div class="category-image">
          <img
            :src="category.image || defaultImage"
            :alt="category.name"
            @error="handleImageError"
          />
          <div v-if="category.productCount" class="product-count">
            {{ category.productCount }}件商品
          </div>
        </div>
        <div class="category-info">
          <h3 class="category-name">{{ category.name }}</h3>
          <p v-if="category.description" class="category-desc">
            {{ category.description }}
          </p>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="category-loading">
      <el-skeleton animated>
        <template #template>
          <div class="skeleton-grid">
            <div
              v-for="i in skeletonCount"
              :key="i"
              class="skeleton-item"
            >
              <el-skeleton-item variant="image" style="height: 120px" />
              <el-skeleton-item variant="text" style="width: 80%; margin-top: 10px" />
            </div>
          </div>
        </template>
      </el-skeleton>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && categories.length === 0" class="category-empty">
      <el-empty description="暂无分类数据" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import { categoryApi, type Category } from '@/api/category'
import { useRouter } from 'vue-router'

// Props
interface Props {
  title?: string
  type?: 'top' | 'hot' | 'recommended' | 'all'
  columns?: number
  limit?: number
  showMore?: boolean
  showProductCount?: boolean
  defaultImage?: string
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  type: 'top',
  columns: 4,
  limit: 8,
  showMore: false,
  showProductCount: true,
  defaultImage: '/placeholder-category.jpg'
})

// Emits
const emit = defineEmits<{
  categoryClick: [category: Category]
  viewMore: []
}>()

// 响应式数据
const categories = ref<Category[]>([])
const loading = ref(false)
const router = useRouter()

// 计算属性
const displayCategories = computed(() => {
  return props.limit > 0 ? categories.value.slice(0, props.limit) : categories.value
})

const skeletonCount = computed(() => {
  return Math.min(props.limit || 8, 8)
})

// 获取分类数据
const fetchCategories = async () => {
  try {
    loading.value = true
    let response

    switch (props.type) {
      case 'top':
        response = await categoryApi.getTopCategories({
          includeProductCount: props.showProductCount
        })
        break
      case 'hot':
        response = await categoryApi.getHotCategories(props.limit || 8)
        break
      case 'recommended':
        response = await categoryApi.getRecommendedCategories(props.limit || 6)
        break
      case 'all':
        response = await categoryApi.getCategories({
          includeProductCount: props.showProductCount
        })
        break
      default:
        response = await categoryApi.getTopCategories({
          includeProductCount: props.showProductCount
        })
    }

    categories.value = response.data || []
  } catch (error) {
    console.error('获取分类数据失败:', error)
    ElMessage.error('获取分类数据失败')
  } finally {
    loading.value = false
  }
}

// 处理分类点击
const handleCategoryClick = (category: Category) => {
  emit('categoryClick', category)
  router.push(`/products?categoryId=${category.id}`)
}

// 处理查看更多
const handleViewMore = () => {
  emit('viewMore')
  router.push('/categories')
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = props.defaultImage
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories()
})

// 暴露刷新方法
defineExpose({
  refresh: fetchCategories
})
</script>

<style scoped>
.category-grid {
  width: 100%;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.category-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.category-list {
  display: grid;
  grid-template-columns: repeat(v-bind(columns), 1fr);
  gap: 20px;
}

.category-item {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.category-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.category-image {
  position: relative;
  width: 100%;
  height: 120px;
  overflow: hidden;
}

.category-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.category-item:hover .category-image img {
  transform: scale(1.1);
}

.product-count {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.category-info {
  padding: 15px;
}

.category-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  text-align: center;
}

.category-desc {
  font-size: 14px;
  color: #666;
  margin: 0;
  text-align: center;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.skeleton-grid {
  display: grid;
  grid-template-columns: repeat(v-bind(columns), 1fr);
  gap: 20px;
}

.skeleton-item {
  background: white;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-loading,
.category-empty {
  width: 100%;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .category-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .category-list {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
  
  .category-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .category-title {
    font-size: 20px;
  }
  
  .category-image {
    height: 100px;
  }
  
  .category-info {
    padding: 12px;
  }
  
  .category-name {
    font-size: 14px;
  }
  
  .category-desc {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .category-list {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }
  
  .category-image {
    height: 80px;
  }
  
  .category-info {
    padding: 10px;
  }
}
</style>